import Toasts from "./Export/BaseToasts";
import XmlHttpTool from "./MyTools/XmlHttpTool";
const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property(cc.Prefab)
    knifePrefab: cc.Prefab = null

    @property(cc.Node)
    watermelonNode: cc.Node = null;

    @property(cc.Node)
    Knife: cc.Node = null;

    @property(cc.Node)
    KnifeNumber: cc.Node = null;

    @property(cc.Node)
    watermelonBg: cc.Node = null;

    @property(cc.Node)
    enemyKnifeNode: cc.Node = null;

    @property(cc.NodePool)
    enemyPool: cc.NodePool = null;

    @property
    indexnumber: number = 0

    @property(cc.SpriteFrame)
    knifeSprite: cc.SpriteFrame = null;

    @property([cc.Vec2])
    knifePointArray: Array<cc.Vec2> = []

    @property(Toasts)
    toasts: Toasts = null;

    @property(cc.Label)
    KnifeNumLabel: cc.Label = null;

    @property
    KnifeAmount: number = 0;

    @property(cc.Node)
    GamePlayView: cc.Node = null;

    @property(cc.Node)
    GameStartView: cc.Node = null;

    @property(cc.Node)
    WaterPopExitView: cc.Node = null;

    @property(cc.Node)
    WaterPopFaileView: cc.Node = null;

    @property(cc.Node)
    WaterPopSuccessView: cc.Node = null;

    @property
    isGameOver: boolean = false;

    @property(cc.Node)
    MelonAminates: cc.Node = null;

    @property(cc.Node)
    WaterPopRushView: cc.Node = null;

    @property(cc.Node)
    MonsterlonIcon: cc.Node = null;

    @property(cc.Node)
    MonsterAminates: cc.Node = null;

    @property(cc.Node)
    BowieAminates: cc.Node = null;

    @property(cc.Node)
    BowielonIcon: cc.Node = null;

    @property(cc.Node)
    collideNodeStart: cc.Node = null;

    @property
    PassLeave: number = 0;

    @property(cc.Label)
    ProgressLabel: cc.Label = null;

    @property
    ProgressNum: number = 0;

    @property(cc.SpriteFrame)
    BowieSprite: cc.SpriteFrame = null;

    @property(cc.SpriteFrame)
    BowieNumSprite: cc.SpriteFrame = null;

    @property
    LaunchNumer: number = 0;

    @property()
    first_inning:any[]=[];

    @property()
    second_inning:any[]=[];

    @property()
    thired_inning:any[]=[];

    @property()
    all_inning:any[]=[];

    @property
    turnSpeed:number=0

    @property(cc.SpriteFrame)
    SecondBgSprite: cc.SpriteFrame = null;

    @property(cc.SpriteFrame)
    ThirdBgSprite: cc.SpriteFrame = null;

    @property(cc.Node)
    BgGroudNode: cc.Node = null;

    @property
    Game_type:number=1

    @property
    playId:string=""

    @property(cc.Node)
    successImageNode: cc.Node = null;

    @property(cc.Label)
    successTitle: cc.Label = null;

    @property({type:cc.AudioClip})
    hitSound = null;

    @property({type:cc.AudioClip})
    hitBreakSound = null;

    @property({type:cc.AudioClip})
    hidsdHitSound = null;

    @property({type:cc.AudioClip})
    successSound = null;
    
    onLoad() {  

        this.init()
        // var that=this
        // XmlHttpTool.instance.httpUtils("/lipsticks/begin",{"game_type":1},function(successRes){
      
        //  cc.log("游戏初始化", successRes);
        //      that.first_inning=successRes.first_inning
        //      that.second_inning=successRes.second_inning
        //      that.thired_inning=successRes.third_inning
        //      that.all_inning=successRes.first_inning
        //      that.turnSpeed=successRes.init_speed
        //      that.collideNodeStart.getComponent(cc.RigidBody).angularVelocity=that.turnSpeed
        //      that.KnifeAmount =that.first_inning.length
        //      that.KnifeNumLabel.string = "x" + that.KnifeAmount.toString()
        //      that.LaunchNumer = 0
      
        //  },function(faileRes){
        //      cc.log("初始化失败",faileRes);
        //      that.toasts.add(JSON.stringify(faileRes));
        //  });
    }

    startEnterGame(gameTypeForm){
        
        var that=this
        XmlHttpTool.instance.httpUtils("/lipsticks/begin",{"game_type":gameTypeForm},function(successRes){
      
         cc.log("游戏初始化", successRes);
             that.first_inning=successRes.first_inning
             that.second_inning=successRes.second_inning
             that.thired_inning=successRes.third_inning
             that.all_inning=successRes.first_inning
             that.turnSpeed=successRes.init_speed
             that.collideNodeStart.getComponent(cc.RigidBody).angularVelocity=that.turnSpeed
             that.KnifeAmount =that.first_inning.length
             that.KnifeNumLabel.string = "x" + that.KnifeAmount.toString()
             that.LaunchNumer = 0
             that.playId=successRes.playid
             that.ProgressLabel.string = (that.ProgressNum).toString() + "/"+(that.first_inning.length+that.second_inning.length+that.thired_inning.length)

         },function(faileRes){
             cc.log("初始化失败",faileRes);
             that.toasts.add(JSON.stringify(faileRes));
         },function(errorRes){
          that.toasts.add(errorRes);
         });

    }
    
    init() {

        var manager = cc.director.getCollisionManager();
        manager.enabled = true;
        // manager.enabledDebugDraw = true;
        // manager.enabledDrawBoundingBox = true;
        cc.director.getPhysicsManager().enabled = true;

        this.enemyPool = new cc.NodePool();
        let initCount = 10;
        for (let i = 0; i < initCount; ++i) {
            let enemy = cc.instantiate(this.knifePrefab); // 创建节点
            this.enemyPool.put(enemy);
        }
        this.indexnumber = 1
        this.watermelonBg.zIndex = 2
        this.isGameOver = false;
     
        cc.log("初始化后对象池长度", this.enemyPool.size())

    }

    launchKnifeClick() {

      
        this.LaunchNumer = this.LaunchNumer + 1

        if (this.LaunchNumer >this.all_inning.length) {

            cc.log("隔断点击")
            // this.toasts.add("数据错误");
            return
        }

            cc.log("每一刀的旋转速度",this.all_inning[this.LaunchNumer-1].speed)
        
            if(this.all_inning[this.LaunchNumer-1].direction==0){

                this.collideNodeStart.getComponent(cc.RigidBody).angularVelocity=this.all_inning[this.LaunchNumer-1].speed
            }else{

                this.collideNodeStart.getComponent(cc.RigidBody).angularVelocity=-this.all_inning[this.LaunchNumer-1].speed
            }

        if (this.KnifeAmount == 0) {

            if (this.toasts.delloc() == true) {
                return
            }
            this.toasts.add("道具不足");
            return

        }
        
        if(isSound){
            cc.audioEngine.playEffect(this.hitSound, false);
        }
        
        this.KnifeAmount = this.KnifeAmount - 1
        this.ProgressNum = this.ProgressNum + 1
        this.ProgressLabel.string = (this.ProgressNum).toString() + "/"+(this.first_inning.length+this.second_inning.length+this.thired_inning.length)
        this.KnifeNumLabel.string = "x" + this.KnifeAmount.toString()

        cc.log("对象池内对象长度", this.enemyPool.size())

        var actionTo = cc.moveBy(0.02, cc.v2(0, 215));//215距离要恰好接触碰撞点，飞刀才能保持深度一直
        let enemy = null;

        if (this.enemyPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            enemy = this.enemyPool.get();

        } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建

            enemy = cc.instantiate(this.knifePrefab);

        }
        enemy.parent = this.node

        var show = cc.show() //取出来先透明度为1

        this.enemyKnifeNode = enemy

        var hide = cc.hide()

        var delay = cc.delayTime(0.5)

        var finishPut = cc.callFunc(function () {

            // //对象池回收

            enemy.setPosition(0, -309);
            this.enemyPool.put(enemy);

        }, this)

        if (this.PassLeave == 2) {
            enemy.getComponent(cc.Sprite).spriteFrame = this.BowieSprite
        }

        enemy.runAction(cc.sequence(show, actionTo, hide, delay, finishPut))

    }

    rigidBodyFinish(intersectionPoint: cc.Vec2, dirVec: cc.Vec2) {

        cc.log("碰撞回调数组元素", this.knifePointArray.length)

        if (this.knifePointArray.length > 0) {

            for (let pointV2 of this.knifePointArray) {

                let distance = intersectionPoint.sub(pointV2).mag();

                // cc.log("距离",distance)
                if (distance < 44) {

                    // this.toasts.add("游戏挂了");
                    this.gameOver(0)
                    if(isSound){
                        cc.audioEngine.playEffect(this.hidsdHitSound, false);
                    }
            
                } else {

                    
                    if (this.knifePointArray.length >=this.all_inning.length-1) {

                        this.PassLeave = this.PassLeave + 1
                        if(isSound){
                            cc.audioEngine.playEffect(this.hitBreakSound, false);
                        }      
                        if (this.PassLeave == 1) {

                            cc.log("第一关结束",this.LaunchNumer,this.all_inning[this.first_inning.length-1].speed)
                            this.MelonAminates.active = true
                            this.watermelonNode.opacity = 0
                            this.KnifeAmount =this.second_inning.length
                            this.KnifeNumLabel.string = "x" + this.KnifeAmount.toString()
                            this.scheduleOnce(() => {

                                this.watermelonNode.active = false
                                this.MonsterlonIcon.active = true
                                this.knifePointArray.splice(0, this.knifePointArray.length)
                                this.collideNodeStart = this.MonsterlonIcon
                                this.collideNodeStart.getChildByName("MonsterBg").zIndex = 2
                                this.LaunchNumer = 0
                                this.collideNodeStart.getComponent(cc.RigidBody).angularVelocity=this.all_inning[this.first_inning.length-1].speed
                                this.all_inning=this.second_inning
                                this.BgGroudNode.getComponent(cc.Sprite).spriteFrame=this.SecondBgSprite

                            }, 0.6);

                            return


                        } else if (this.PassLeave == 2) {

                            cc.log("第二关结束",this.LaunchNumer,this.all_inning[this.second_inning.length-1].speed)

                            this.MonsterAminates.active = true
                            this.MonsterlonIcon.opacity = 0
                            this.Knife.getComponent(cc.Sprite).spriteFrame = this.BowieSprite
                            this.KnifeNumber.getComponent(cc.Sprite).spriteFrame = this.BowieNumSprite
                            this.KnifeAmount =this.thired_inning.length
                            this.KnifeNumLabel.string = "x" + this.KnifeAmount.toString()
                            this.scheduleOnce(() => {

                                this.MonsterlonIcon.active = false
                                this.BowielonIcon.active = true
                                this.knifePointArray.splice(0, this.knifePointArray.length)
                                this.collideNodeStart = this.BowielonIcon
                                this.collideNodeStart.getChildByName("BowieBg").zIndex = 2
                                this.knifeSprite = this.BowieSprite
                                this.LaunchNumer = 0
                                this.collideNodeStart.getComponent(cc.RigidBody).angularVelocity=this.all_inning[this.second_inning.length-1].speed
                                this.all_inning=this.thired_inning
                                this.BgGroudNode.getComponent(cc.Sprite).spriteFrame=this.ThirdBgSprite

                            }, 0.6);

                            return

                        } else if (this.PassLeave == 3) {

                            cc.log("第三关结束",this.LaunchNumer)
                            this.BowieAminates.active = true
                            this.BowielonIcon.opacity = 0
                            this.gameOver(1)
                            this.scheduleOnce(() => {

                                this.BowieAminates.active = false
                                this.knifePointArray.splice(0, this.knifePointArray.length)
                                
                                // this.WaterPopSuccessView.active = true
                                this.LaunchNumer = 0

                            }, 0.6);

                            return

                        }
                    }
                }

            }
        }

        this.knifePointArray.push(intersectionPoint)
        var knifeNode = new cc.Node('Sprite');
        knifeNode.addComponent(cc.Sprite);
        knifeNode.getComponent(cc.Sprite).spriteFrame = this.knifeSprite;

        knifeNode.parent = this.collideNodeStart
        knifeNode.setPosition(intersectionPoint)
        knifeNode.anchorX = 0.5
        knifeNode.anchorY = 0.7
        var vector = this.vectorsToDegress(dirVec);
        knifeNode.rotation = vector;
        knifeNode.zIndex = 1

        let x = this.collideNodeStart.x; let y = this.collideNodeStart.y;
        let offset = 0.2;
        let action = cc.repeatForever(
            cc.sequence(
                cc.moveTo(0.01, cc.v2(x + (5 + offset), y + (offset + 7))),
                cc.moveTo(0.01, cc.v2(x - (6 + offset), y + (offset + 7))),
                cc.moveTo(0.01, cc.v2(x - (8 + offset), y + (offset + 3))),
                cc.moveTo(0.01, cc.v2(x + (3 + offset), y - (6 + offset))),
                cc.moveTo(0.01, cc.v2(x - (5 + offset), y + (offset + 5))),
                cc.moveTo(0.01, cc.v2(x + (2 + offset), y - (8 + offset))),
                cc.moveTo(0.01, cc.v2(x - (8 + offset), y - (10 + offset))),
                cc.moveTo(0.01, cc.v2(x + (3 + offset), y + (offset + 10))),
                cc.moveTo(0.01, cc.v2(x + (0 + offset), y + (offset + 0)))
            )
        )
        this.collideNodeStart.runAction(action);
        setTimeout(() => {
            this.collideNodeStart.stopAction(action);
            this.collideNodeStart.x = x; this.collideNodeStart.y = y;
        }, 50);

    }


    vectorsToDegress(dirVec: cc.Vec2) {

        let comVec = cc.v2(0, -1);    // 水平向左的对比向量
        let radian = dirVec.signAngle(comVec);    // 求方向向量与对比向量间的弧度
        let degree = cc.misc.radiansToDegrees(radian);    // 将弧度转换为角度
        return degree;

    }

    backSenceClick() {

        this.GameStartView.active = true
        this.GamePlayView.active = false
        this.WaterPopExitView.active = false
    }

   gameOver(gameresult:number){

    var that=this
    XmlHttpTool.instance.httpUtils("/lipsticks/gameover",{"result":gameresult,"playid":that.playId,"game_type":Gametype},function(successRes){
  
       cc.log("闯关是结果",successRes)
       if(successRes["is_success"]==1){
        cc.log("闯关成功")

        var _this = that
        cc.loader.load({ url: successRes["toy_info"]["thumbnail"], type: 'png' }, function (err, img) {
  
          var mylogo = new cc.SpriteFrame(img);
          _this.successImageNode.getComponent(cc.Sprite).spriteFrame = mylogo
  
        });
        that.successTitle.string=successRes["toy_info"]["name"]
        if(isSound){
            cc.audioEngine.playEffect(that.successSound, false);
        }
        that.WaterPopSuccessView.active = true
     
       }else{
          that.WaterPopFaileView.active = true
        cc.log("闯关失败")
       }

     },function(faileRes){
         
         cc.log("游戏结束上报失败",faileRes);

     },function(errorRes){
    
     });

   }

    start() {

    }

    // update (dt) {}
}
